package com.jy.admin.crawler;

import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.exception.common.ApplicationException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2021/7/4
 * Time: 2:06 下午
 * <p>
 * 浏览器管理中心
 */
@Service
public class BrowserManager {
    private static Logger logger = LoggerFactory.getLogger(BrowserManager.class);
    public static final Map<String, WebDriver> webDriverContainer = new HashMap<>();

    //用于超时关闭打开的浏览器
    public static Map<String, Long> webDriverTimeRecord = new HashMap<>();


    /**
     * 当前已经拥有的浏览器数量
     */
    private static int size = 0;

    private static int maxSize = 20;


    private static String chrome_driver_path = "/Users/yujianfu/Downloads/chromedriver";

//    @NacosValue(value = "${chrome.driver.path}", autoRefreshed = true)
//    private String chromeDriverPath;

    @PostConstruct
    public void init() {

//        chrome_driver_path = chromeDriverPath;
        long l = System.currentTimeMillis();
    }

    private static void register(DriverId driverId, WebDriver webDriver) {
        if (size == maxSize) {
            throw new ApplicationException("webDriver reach to max size , cannot create a new one");
        }
        size++;
        webDriverContainer.put(driverId.getId(), webDriver);
        webDriverTimeRecord.put(driverId.getId(), System.currentTimeMillis());
    }

    public static boolean isWebDriverExist(DriverId driverId) {
        return webDriverContainer.containsKey(driverId.getId());
    }

    public static WebDriver getWebDriver(DriverId driverId) {
        logger.info("==  driverId===,driverId:{}", driverId.getId());
        if (webDriverContainer.containsKey(driverId.getId())) {
            return webDriverContainer.get(driverId.getId());
        }

        try {
            System.setProperty("webdriver.chrome.whitelistedIps", "");
            System.setProperty("webdriver.chrome.driver", chrome_driver_path);
            ChromeOptions chromeOptions = new ChromeOptions();
            //关闭窗口
//            chromeOptions.addArguments("--headless");
            chromeOptions.addArguments("--window-size=1920,1080");
            chromeOptions.addArguments("--disable-dev-shm-usage");

            //无痕浏览
            chromeOptions.addArguments("--incognito");
            chromeOptions.addArguments("--whitelisted-ips");
            chromeOptions.addArguments("--no-sandbox");
            WebDriver driver = new ChromeDriver(chromeOptions);

            register(driverId, driver);
            return driver;
        } catch (Exception e) {
            logger.error("== getWebDriver ==,e", e);
            throw new ApplicationException(" get web driver failed");
        }
    }

    public static void remove(DriverId driverId) {
        if (!webDriverContainer.containsKey(driverId.getId())) {
            return;
        }

        webDriverContainer.remove(driverId.getId());
    }


}
